import axios from 'axios'
import store from '../store'
import router from '../router/index'

// axios 配置
axios.defaults.timeout = 5000
axios.defaults.baseURL = 'http://101.132.185.253:8080/HealthExaminations'
// axios.defaults.baseURL = 'localhost'
// axios.defaults.baseURL = ''

// http request 拦截器 每个请求头都加上token
axios.interceptors.request.use(
  config => {
    if (store.state.token) {
      config.headers.Authorization = `token ${store.state.token}`
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// http response 拦截器
axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          /* 401 清除token信息并跳转到登录页面 */
          store.commit('logout')
          /* 只有在当前路由不是登录页面才跳转 */
          router.currentRoute.path !== '/login' && router.replace({
            path: '/login',
            query: { redirect: router.currentRoute.path }
          })
      }
    }
    console.log(JSON.stringify(error))
    return Promise.reject(error.response.data)
  }
)

export default axios
